package main.java.com.lee.pattern.forkjoin;

import java.util.concurrent.RecursiveTask;
import java.util.stream.IntStream;

/**
 * @Description 考虑到任务极大可能是数量比较多的, 拆分的维度自然也就是按照数量拆分,
 * 假如计算任务是1+2+...+100.
 * 每次把任务拆分为2部分, 拆解过程
 * 1...100
 * 判断任务数量是否足够小,
 * if (100-1 <= 阈值){
 *     执行计算
 * }else{ //执行拆分逻辑
 *     int middle= (100-1)/2=49;
 *     递归左侧, (0, 49)
 *     递归右侧, (50, 100)
 * }
 * return xxx;
 * </=>middle = (100-1)/2=49, 拆分结果, 1..49, 50-100
 *
 * @Author winston
 * @DateTime 2022/2/19
 */
public class AddTask extends RecursiveTask<Integer> {

    private final int threshold = 90;
    private final int start;
    private final int end;

    public AddTask(int start, int end) {
        this.start = start;
        this.end = end;
    }
    @Override
    protected Integer compute() {
        int sum = 0;
        boolean canCompute = (end - start) <= threshold;
        if (canCompute) {
            sum += IntStream.rangeClosed(start, end).sum();
        } else {
            int middle = (start + end) / 2;
            AddTask leftTask = new AddTask(start, middle);
            AddTask rightTask = new AddTask(middle + 1, end);
            leftTask.fork();
            rightTask.fork();
            Integer leftSum = leftTask.join();
            Integer rightSum = rightTask.join();
            sum = leftSum + rightSum;
        }
        return sum;
    }
}
